package com.gitee.cashzhang27.test.boot.functional.configuration;

import com.gitee.cashzhang27.test.boot.functional.error.ExceptionHandlerHelper;
import com.gitee.cashzhang27.test.boot.functional.handler.PersonHandler;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.function.RequestPredicates;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.RouterFunctions;
import org.springframework.web.servlet.function.ServerResponse;

/**
 * 路由配置类.
 *
 * @author Cash Zhang
 * @version v1.0 2020/09/15 16:58
 * @since v1.0
 */
@Configuration
@AllArgsConstructor
public class RouterConfiguration {

  private final PersonHandler personHandler;

  @Bean
  public RouterFunction<ServerResponse> helloWorld() {
    return RouterFunctions.route()
        .GET("/hello-world", RequestPredicates.accept(MediaType.TEXT_PLAIN),
            request -> ServerResponse.ok().body("Hello World")).build();
  }

  @Bean
  public RouterFunction<ServerResponse> personRouter() {
    return RouterFunctions.route()
        .path("/person", b1 -> b1
            .filter((request, next) -> {
              if (this.personHandler.hasPerson(request)) {
                return next.handle(request);
              } else {
                return ServerResponse.status(HttpStatus.CONFLICT).build();
              }
            })
            .POST("/person/{id}", this.personHandler::createPerson)
            .POST("/persons", this.personHandler::createPersons))
        .after((request, response) -> this.logResponse(response))
        .onError(Throwable.class, ExceptionHandlerHelper::handlerError)
        .build();
  }

  private ServerResponse logResponse(ServerResponse response) {
    System.out.println(3);
    return response;
  }

}

